<?php

namespace App\Http\Controllers\Mini;

use App\Models\Configs;
use App\Models\IntegralLogs;
use App\Models\UserInfos;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Models\Validate;
use Icharle\Wxtool\Wxtool;
use Mrgoon\AliSms\AliSms;
use App\Models\UserLevels;
use App\Models\BalanceLogs;

class LoginController extends Controller
{
    use AuthenticatesUsers;
    

    /**
     * 用户登录
     * @route api.login.login
     * @param mobile 手机号
     * @param password 密码
     * @param user_type 1密码登陆 2手机验证码登录
     */
    public function login(Request $request)
    {
        try{
            $params = [
                'mobile' => (string)$request->post('mobile'),
                'password' => (string)$request->post('password'),
            ];
            $user_type = (int)$request->post('user_type');// 1密码登陆 2手机验证码登录
            if ($user_type == 1){//验证
                $rules = ['mobile' => 'required', 'password' => 'required',];
                $msgs = ['mobile.required' => '请填写手机号码', 'password.required' => '请填写密码',];
                $validator = validator()->make($params,$rules,$msgs);
                if ($validator->fails()) {
                    return response()->json(["code"=>0, "msg"=>$validator->errors()->first()]);
                }
            }

            //存缓存
            $auth = false;
            if($user_type == 2 && $params['password'] == null) {
                $auth = auth()->guard('api')->attempt(['mobile' => $params['mobile']]);
            }else {
                $auth = auth()->guard('api')->attempt(['mobile' => $params['mobile'], 'password' => $params['password']]);
            }
            if ($auth) {
                $request->session()->regenerate();
                $this->clearLoginAttempts($request);
                $users = auth()->guard('api')->user();
                if($users['status'] == -1){
                    return response()->json(["code"=>0, "msg"=>'当前用户不存在']);
                }
                //当天第一次登陆送积分
                $integral = Configs::getConfig('integral');//积分
                if (trim(@date('Y-m-d', strtotime($users['login_at']))) != trim(date('Y-m-d'))) {
                    if($users['type'] == 1) {//HR登陆送积分
                        $integral_login = $integral['hr_login'];
                    }elseif ($users['type'] == 2) {//供应商登陆送积分
                        $integral_login = $integral['bus_login'];
                    }
                    Users::where('id',$users['id'])->increment('integral',$integral_login);
                    //添加日志记录
                    $integral = [
                        'user_id' => $users['id'],
                        'user_name' => $users['username'],
                        'integral' => '+'.$integral_login,
                        'desc' => '每日首次登陆送积分',
                        'type' => 1,
                    ];
                    IntegralLogs::create($integral);
                }
                Users::where('id',$users['id'])->update(['login_at' => date('Y-m-d H:i:s'), 'login_ip' => $request->ip()]);
                return response()->json([
                    "code" => 1,
                    "msg" => "登录成功",
                    "data" => $users
                ]);
            }
            return response()->json(["code"=>0, "msg"=>'用户名或密码错误']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户注册
     * @route api.login.register
     * @param mobile 手机号
     * @param password 密码
     * @param type 类型：1人力HR，2供应商
     */
    public function register(Request $request)
    {
        try{
            $params = [
                'mobile' => (string)$request->post('mobile'),
                'password' => (string)$request->post('password'),
                'type' => (int)$request->post('type'),//类型：1人力HR，2供应商
            ];
            //检测手机号是否被注册
            $check_mobile = Users::getUserInfo(['mobile' => $params['mobile']]);
            if (!empty($check_mobile)) {
                return response()->json(["code"=>0, "msg"=>'该手机号已经注册']);
            }

            $integral = Configs::getConfig('integral');//积分
            $base = Configs::getConfig('base');//获取头像
            $now = date('Y-m-d H:i:s');
            $data = [
                'avatar' => $base['default_avatar'],
                'user_sn' => 'HR'.substr(time(),-6),
                'username' => $params['mobile'],
                'mobile' => $params['mobile'],
                'password' => bcrypt($params['password']),
                'register_ip' => $request->ip(),
                'sign_in_at' => $now,//最近一次签到时间
                'login_at' => $now,//最近一次登陆时间
                'login_ip' => $request->ip(),
                'type' => $params['type'],
                'created_at' => $now,
                'updated_at' => $now,
            ];
            //注册送积分
            if($params['type'] == 1) {
                $data['integral'] = $integral['hr_register'];
            }elseif($params['type'] == 2) {
                $data['integral'] = $integral['bus_register'];
                $data['status'] = 2;
            }
            $user_id = Users::insertGetId($data);//数据入库
            //信息存入扩展表
            $data_info = [
                'user_id' => $user_id,
            ];
            UserInfos::create($data_info);
            //添加日志记录
            $integral_log = [
                'user_id' => $user_id,
                'user_name' => $params['mobile'],
                'desc' => '注册送积分',
                'type' => 1,
            ];
            if($params['type'] == 1) {
                $integral_log['integral'] = '+'.$integral['hr_register'];
            }elseif($params['type'] == 2) {
                $integral_log['integral'] = '+'.$integral['bus_register'];
            }
            IntegralLogs::create($integral_log);

            return response()->json(["code"=>1, "msg"=>'注册成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }
    
    
    /**
     * 修改密码
     * @route api.login.changePwd
     * @param mobile 手机号
     * @param password 新密码
     * @param confirmc_pwd 确认密码
     */
    public function changePwd(Request $request)
    {
        try{
            $mobile = (string)$request->post('mobile');
            $password = (string)$request->post('password');
            $confirmc_pwd = (string)$request->post('confirmc_pwd');
            if(empty($mobile) || empty($password) || empty($confirmc_pwd)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $mobile))  return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);
            if($password !== $confirmc_pwd){
                return response()->json(["code"=>0, "msg"=>'两次密码输入不一致,请重新输入']);
            }

            $info = Users::where('mobile',$mobile)->first(['id','status']);
            if(!empty($info) && $info['status'] !== -1){
                Users::where('id',$info['id'])->update(['password' => bcrypt($password)]);
                return response()->json(["code"=>1, "msg"=>'修改成功,请重新登录']);
            }else{
                return response()->json(["code"=>0, "msg"=>'该用户不存在']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 找回密码
     * @route api.login.findPwd
     * @param mobile 手机号
     * @param password 新密码
     */
    public function findPwd(Request $request)
    {
        try{
            $mobile = (string)$request->post('mobile');
            $password = (string)$request->post('password');
            if(empty($mobile) || empty($password)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $mobile))  return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);

            $info = Users::where('mobile',$mobile)->first(['id','status']);
            if(!empty($info) && $info['status'] !== -1){
                Users::where('id',$info['id'])->update(['password' => bcrypt($password)]);
                return response()->json(["code"=>1, "msg"=>'找回成功,请重新登录']);
            }else{
                return response()->json(["code"=>0, "msg"=>'该用户不存在']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 发送短信验证码
     * @route api.login.sendMsgCode
     * @param mobile 手机号
     */
    public function sendMsgCode(Request $request) {
        $mobile = (string)$request->post("mobile");
        if (empty($mobile)) return response()->json(["code"=>0, "msg"=>"参数错误"]);

        try{
            $userinfo = Users::where("mobile", $mobile)->value('mobile');
            if (empty($userinfo)) return response()->json(["code"=>0, "msg"=>"该手机账号已注册"]);

            $config = [
                'timeout' => 5.0,// HTTP 请求的超时时间（秒）
                // 默认发送配置
                'default' => [
                    'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,// 网关调用策略，默认：顺序调用
                    'gateways' => ['Qcloud'],// 默认可用的发送网关
                ],
                // 可用的网关配置
                'gateways' => [
                    'errorlog' => [
                        'file' => '/tmp/easy-sms.log',
                    ],
                    'Qcloud' => [
                        'sdk_app_id' => $this->config["service"]["aliyun_sms_ak"], // SDK APP ID
                        'app_key' => $this->config["service"]["aliyun_sms_as"], // APP KEY
                        'sign_name' => '', // 短信签名，如果使用默认签名，该字段可缺省（对应官方文档中的sign）
                    ],
                ],
            ];

            $cache = cache()->get('sms-'.$mobile);
            //20秒的频繁验证
            if($cache && Carbon::now()->timestamp - $cache['time'] < 20){
                return response()->json(["code"=>0, "msg"=>"您的操作太频繁"]);
            }

            $code = rand(100000,999999);
            $easySms = new EasySms($config);

            $result = $easySms->send($mobile, [
                'content'  => '您的验证码为: '.$code,
                'template' => 'SMS001',
                'data' => [
                    'code' => $code
                ],
            ]);
            if($result->Code == 'OK'){
                //保存验证码到缓存用于验证
                $time = Carbon::now()->timestamp;
                //2分钟的过期时间
                cache()->add('sms-'.$mobile, ['code'=>$code, 'time'=>$time],120);
                return response()->json(["code"=>1, "msg"=>"发送成功"]);
            }else{
                return response()->json(["code"=>0, "msg"=>"发送短信失败"]);
            }
        }catch(\Exception $e){
            return response()->json(["code"=>0, "msg"=>"发送短信失败"]);
        }
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        auth()->guard('api')->logout();
        $request->session()->regenerate();
        return redirect(route('api.login.login'));
    }

    
    /**
     * 获取用户详细信息
     * @param Request $request
     * 
     */
    public function GetInfo(Request $request){
    	$a = new Wxtool();
    	$code = $request->post("code");                                     //wx.login获取
    	$encryptedData = $request->post("encryptedData");                   //wx.getUserInfo 获取
    	$iv = $request->post("iv");                                         //wx.getUserInfo 获取
    	$res = $a->GetSessionKey($code);                            //获取用户openid 和 session_key
    	$userinfo = $a->GetUserInfo($encryptedData,$iv);            //获取用户详细信息
    	$userinfo = json_decode($userinfo,true);
    	if(!empty($userinfo['openId'])){
	    	$member_id = Users::where("wechat_id", $userinfo['openId'])->value('id');
	    	if($member_id>0){    		
	    		$data = Users::where("id",$member_id)->first();
	    		$data['leve_info'] = UserLevels::where("id",$data['grade'])->select("id","name","icon")->get();
	    		return response()->json(["code"=>0, "msg"=>"获取成功",'data'=>$data]);
	    	}else{
	    		$inviter_id = (int)$request->post("inviter_id");	    		
	    		$data['nickname'] = $userinfo['nickName'];
	    		$data['wechat_id'] = $userinfo['openId'];
	    		$data['avatar'] = $userinfo['avatarUrl'];
	    		$data['inviter_id'] = $inviter_id;
				$data['status'] = 2;
	    		$data['grade'] = UserLevels::orderBy("limit_number","asc")->value("id");
	    		
	    		$data['login_at'] = date("Y-m-d H:i:s",time());
	    		$insert = Users::create($data);
	    		
	    		if($insert){
	    			$data['leve_info'] = UserLevels::where("id",$data['grade'])->select("id","name","icon")->get();
	    			return response()->json(["code"=>0, "msg"=>'获取成功',"data"=>$data]);
	    		}	    		
	    	}	
    	}else{
    		return response()->json(["code"=>5, "msg"=>'授权失败',"data"=>$userinfo]);
    	}
    }
    
    public function genValidateCode(){
    	return mt_rand(000000,999999);
    }
    
    /**
     * 获取验证码
     */
    public function  getCode(Request $request) {
    	//生成随机的验证码
    	$code = $this->genValidateCode();
    	//发送验证码
    	$target = $request->post("mobile");
    	if(empty($target)){
    		return response()->json(["code"=>0, "msg"=>'请输入手机号']);
    	} 
    	$result = (new AliSms())->sendSms($target, 'SMS_173176414', ['code'=> $code]);
    
    	if (!$result) {
    		
    		return response()->json(["code"=>5, "msg"=>'发送失败',"data"=>$result]);
    	}else{
    		//存验证码
    		Validate::where(['mobile'=>$target,'v_type'=>1])->delete();
    		//发送成功后将验证码保存到数据库
    		$validate_code = new Validate();
    		$validate_code->mobile = $target;
    		$validate_code->v_type = 1;
    		$validate_code->created_at = date('Y-m-d H:i:s',time());
    		$validate_code->code = $code;
    		if(!$validate_code->save()){
    			throw new WrongException('发送验证码失败');
    		}

    		return response()->json(["code"=>3, "msg"=>'发送成功，30分钟内有效',"data"=>$code]);
    	}

    }
    
    /**
     * 获取二维码
     */
    public function  getQRCode(Request $request) {
    	$a = new Wxtool();
    	$inviter_id = (int)$request->post("inviter_id");
    	$pages = "pages/my/main";  //参数跳转到product/show，产品详情
    	$scene = "inviter_id=".$inviter_id;
   
        $imgpath = $a->GetQrcode($scene,$pages); 
        return response()->json(["code"=>1, "msg"=>'获取成功',"data"=>$imgpath]);
    }
    
    /**
     * 领取红包
     */
    public function getRedPackage(Request $request){
    	//$user_id = $request->post("user_id");
    	$user_id = (int)$request->post('user_id');
    	if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'登录失败，领取无效']);
    	$users = Users::findOrFail($user_id);
    	if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户信息异常，领取失败']);
    	if($users["is_get"] == 1){
    		return response()->json(["code"=>0, "msg"=>'已经领取过了']);
    	}else{
    		$base = Configs::getConfig('base');
    		Users::where('id',$user_id)->increment('balance',$base['new_money']);
    		$content = '领取新人红包，收益到账：'.$base['new_money'];   		
    		$balance = [
    				'user_id' => $user_id,
    				'user_name' => $users['true_name']?$users['true_name']:$users['nickname'],
    				'money' => $base['new_money'],
    				'balance' => '+'.$base['new_money'],
    					
    				'desc' => '红包收益',
    				'type' => 1,
    		];
    		$balance_info = BalanceLogs::create($balance);
    		Users::where('id',$user_id)->update(['is_get'=>1]);
    		return response()->json(["code"=>1, "msg"=>'领取成功']);   		
    	}   	
    }
    /**
     * 取消也得调用
     * @param Request $request
     */
    public function setGet(Request $request){
    	$user_id = (int)$request->post('user_id');
    	Users::where('id',$user_id)->update(['is_get'=>1]);
    }
}